package com.example.mybaseapp.ui.okhttptest

import androidx.core.view.isVisible
import com.example.lib_base.BaseNetActivity
import com.example.lib_base.loadutil.ChildToMainUtil
import com.example.mybaseapp.databinding.ActivityOkHttpTestBinding
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okio.IOException

class OkHttpTestActivity : BaseNetActivity<ActivityOkHttpTestBinding>() {
    override val mMainCallBack = object : ChildToMainUtil.MainCallBack {
        override fun mainCallback(string: String?) {
            closeLoading()
            string?.let{it2->
                binding.txGetInfo.text = it2
            }
        }

    }
    private val client = OkHttpClient()
    /**玩安卓 文章列表*/
    private val articalListUrl = "https://www.wanandroid.com/article/list/0/json"
    override fun showLoading() {
        binding.progressBar.isVisible = true
    }

    override fun closeLoading() {
        binding.progressBar.isVisible = false
    }

    override fun onViewInit() {
        binding.btnGetInfo.setOnClickListener {
            getInfo(articalListUrl,mChildCallBack)
        }

        binding.btnRetrofitGet.setOnClickListener {
            getRetrofitInfo()
        }
    }

    private fun getRetrofitInfo() {
        
    }

    private fun getInfo(url:String, callback: ChildToMainUtil.NetTOMainCallBack) {
        showLoading()
        val request = Request.Builder()
            .url(url)
            .get()//明确的指定是get方式，默认也是get方式
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback.callback(null) // 请求失败，返回 null
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (!it.isSuccessful) {
                        callback.callback(null) // 响应不成功，返回 null
                        return
                    }
                    callback.callback(it.body.string()) // 返回响应数据
//                    binding.txGetInfo.text = it.body.string()
//                    closeLoading()//测试发现，这里是子线程，调用这个会报子线程错
                }
            }
        })
    }


}